package org.wyz.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.wyz.mapreduce.kmeans.KMeansMapper;
import org.wyz.mapreduce.kmeans.KMeansReducer;
import org.wyz.mapreduce.kmeans.PointWritable;

import java.net.URI;

public class KMeans {
    private static final String OUT_NAME = "part-r-00000";
    private static final String[] ARGS = {"data/input/kmeans", "data/output/kmeans", "data/cache/kmeans/center.txt"};

    private static final int MAX_EPOCH = 5;
    private static int EPOCH = 0;

    public int run(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "kmeans");
        job.setJarByClass(this.getClass());

        job.setMapperClass(KMeansMapper.class);
        job.setReducerClass(KMeansReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(PointWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);


        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1] + EPOCH));

        if (EPOCH == 0) {
            job.addCacheFile(new URI(args[2]));
        } else {
            job.addCacheFile(new URI(args[1] + (EPOCH - 1) + "/part-r-00000"));
        }

        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        KMeans kMeans = new KMeans();
        for (EPOCH = 0; EPOCH < MAX_EPOCH; EPOCH++) {
            int res = kMeans.run(ARGS);
            if (res != 0) {
                System.exit(res);
            }
        }
    }
}
